import axios from 'axios'
import { Loading,Message } from 'element-ui';
import {geToken} from '@/utils/idnex'
import router  from '@/router'
const request = axios.create({
  baseURL: process.env.VUE_APP_BASEURL,
  timeout: 8000

})
let loading =null
request.interceptors.request.use(function (config) {
  loading = Loading.service({
    text:'加载中',
    spinner:'el-icon-loading',
    background:'rgba(0, 0, 0, 0.8)'
  });

    if (geToken()){
      config.headers.token=geToken()
    }
  return config;
}, function (error) {
loading.close()
  return Promise.reject(error);
});
request.interceptors.response.use(function (res) {
  //判断token 是否过期
  if(res.data.code===401||res.data.code===403){
    //弹出错误信息告诉用户token 过期是||没有登录
    Message({
      type:'error',
      message:'登录上态没有或者过期',
      duration:1500,
      onClose:()=>{
        // 关闭后清除缓存
        localStorage.removeItem('token')
        localStorage.removeItem('role')
        localStorage.removeItem('userinof')
        router.push('/Login')
      }
    })
  }
  loading.close()
  return res;
}, function (error) {
  loading.close()
  return Promise.reject(error);
});
export default request
